package com.atguigu.java;

/**
 * 使用同步方法解决实现Runnable接口的线程安全的问题
 *
 * @Description
 * @Author codingBee
 * @Date 2020/8/26/7:48
 */
public class WindowTest2 {
    public static void main(String[] args) {
        Window2 window1 = new Window2();
        Thread thread1 = new Thread(window1, "窗口1");
        Thread thread2 = new Thread(window1, "窗口2");
        Thread thread3 = new Thread(window1, "窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class Window2 implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {
        while(ticket > 0){
            show();
        }
    }

    private synchronized void show() { //使用了默认的同步监视器：this
        if (ticket > 0) {
            System.out.println(Thread.currentThread().getName() + ":卖票，票号为：" + ticket);
            ticket--;
        }
    }
}
